'use strict'

let port = 5665;
let http = require('http');
let url = require('url');
let querystring = require('querystring')
let fs = require('fs')

let user = {
    admin: 123456
}
http.createServer((req, res) => {
    //获取数据
    let path, get, post
    if (req.method == 'GET') {
        let { pathname, query } = url.parse(req.url, true);
        path = pathname
        get = query
        complete()
    } else if (req.method == 'POST') {
        let arr = []
        req.on('data', buffer => {
            arr.push(buffer)
        })
        req.on('end', () => {
            post = querystring.parse(Buffer.concat(arr).toString())
        })
        complete()
    }

    //定义回调函数 完成后干的事情
    function complete() {
        if (path == '/login') {
            //从get数据里拿出用户名与密码
            let { username, password } = get;

            //判断数据库里有无
            if (!user[username]) {
                res.writeHead(200, {
                    "Content-Type": "text/plain;charset = utf-8"
                })
                res.end(JSON.stringify({
                    err: 1,
                    msg: "用户名不存在"
                })
                )
            } else if (user[username] != password) {
                res.writeHead(200, {
                    "Content-Type": "text/plain;charset = utf-8"
                })
                res.end(JSON.stringify({
                    err: 1,
                    msg: "密码错误"
                })
                )
            } else {
                res.writeHead(200, {
                    "Content-Type": "text/plain;charset = utf-8"
                })
                res.end(JSON.stringify({                   
                    err: 0,
                    msg: "登陆成功"
                })
                )
            }
        } else if (path == '/reg') {

        } else {
            //读取文件
            fs.readFile(`user${path}`, (err, data) => {
                if (err) {
                    res.end('404')
                } else {
                    res.end(data)
                }
            })
        }
    }

}).listen(port)